package cn.frh.org.service.impl;

import cn.frh.basic.service.impl.BaseServiceImpl;
import cn.frh.org.domain.Department;
import cn.frh.org.mapper.DepartmentMapper;
import cn.frh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;




    @Override
    @Transactional
    public List<Department> deptTree() {

        List<Department> all = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department department:all) {
            map.put(department.getId(),department);
        }
        List<Department> deptTree = new ArrayList<>();
        for (Department department:all){
            //如果上级部门id为空 就是顶级部门
            if (department.getParent_id() == null){
                deptTree.add(department);
            }else {
                Long parentId = department.getParent_id();
                Department parentDept = map.get(parentId);
                parentDept.getChildren().add(department);
            }
        }
        return deptTree;
    }


}
